const Koa = require('koa');
const send = require('koa-send')
const app = new Koa();
const isDev = process.env.NOOE_ENV === 'development'
// const pageRouter = require('./dev-ssr')
const path = require('path')
const staticRouter = require("./static")

const apiRouter = require('./routers/api')
const createDb = require('./db/db')
const config = require('../app.config')
const koaBody = require('koa-body')
const db = createDb(config.db.appId, config.db.appKey)
app.use(async (ctx, next) => {
  if (ctx.path === '/favicon.ico') {
    await send(ctx, '/favicon.ico', {root: path.join(__dirname, '../')})
  } else {
    await next()
  }
})
app.use(koaBody())
app.use(async (ctx, next) => {
  try {
    console.log('request path ' + ctx.path)
    await next()
  } catch (err) {
    console.log(err)
    ctx.status = 500
    if (isDev) {
      ctx.body = err.message
    } else {
      ctx.body = 'please try again later'
    }
  }
});
app.use(async (ctx, next) => {
  ctx.db = db
  await next()
})
app.use(staticRouter.routes()).use(staticRouter.allowedMethods())
app.use(apiRouter.routes()).use(apiRouter.allowedMethods())

let pageRouter;
if (isDev) {
  pageRouter = require('./dev-ssr')
} else {
  pageRouter = require('./ssr')
};

app.use(pageRouter.routes()).use(pageRouter.allowedMethods())

app.listen(3000);
